﻿using LD.Host;
using Microsoft.Win32;
using Newtonsoft.Json.Linq;
using ScottPlot.Drawing.Colormaps;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using static LdCommunication.Profinet.Knx.KnxCode;
using static System.Windows.Forms.AxHost;

namespace LD
{
    public class HiveHelper
    {
        private static HiveHelper instance;
        private static object locker = new object();
        private static object obj = new object();

        public static HiveHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (locker)
                    {
                        if (instance == null)
                            instance = new HiveHelper();
                    }
                }
                return instance;
            }
        }

        private void UploadFile(int index, string path)
        {
            //if (!File.Exists(path))
            //    return false;
            //var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
            //// 写入文件  
            //const string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: {2}\r\n\r\n";
            //var header = string.Format(filePartHeader, "file" + index, path, GetMimeMapping(path));
            //var headerbytes = Encoding.UTF8.GetBytes(header);

            //memStream.Write(beginBoundary, 0, beginBoundary.Length);
            //memStream.Write(headerbytes, 0, headerbytes.Length);
            //byte[] buffer = new byte[4096];
            //int bytesRead = 0;
            //while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)//将文件内容写入流
            //{
            //    memStream.Write(buffer, 0, bytesRead);
            //}
            //fileStream.Close();
            //var enterbytes = Encoding.UTF8.GetBytes("\r\n");
            //memStream.Write(enterbytes, 0, enterbytes.Length);
            //newdata += "{\"file_name\":\"" + Path.GetFileName(filePaths[i]) + "\"},";
        }
        public static string GetMimeMapping(string fileName)
        {
            string mimeType = "application/octet-stream";
            string ext = Path.GetExtension(fileName).ToLower();
            RegistryKey regKey = Registry.ClassesRoot.OpenSubKey(ext);
            if (regKey != null && regKey.GetValue("Content Type") != null)
            {
                mimeType = regKey.GetValue("Content Type").ToString();
            }
            return mimeType;
        }
        public void Send(TB_Product product)
        {
            if (product != null)
            {
                /*
                 HiveFunction.instance.SendHiveString("sn", "titlename", "title", DateTime.Now, DateTime.Now, "dataname", "data"
                , new System.Collections.Generic.List<string>() { "upp", "u1" }
                , new System.Collections.Generic.List<string>() { "low", "l1" }
                , new System.Collections.Generic.List<string>() { "path", "path1" }
                , "var"
                );
                {
                "titlename":"title",
                "input_time":"2024-04-28T16:44:11.62+0800",
                "output_time":"2024-04-28T16:44:11.62+0800",
                "data":{"dataname":data},
                "limit":{"dataname":{"upper_limit":upp,"lower_limit":low}},
                "attr":{"Sw_Version":"var"},
                "blobs":[{"file_name":"path"},{"file_name":"path1"}]
                }
                */
                JObject serials = new JObject()
                {

                };
                JObject data = new JObject()
                {
                    { "sw_version",Cache.GetCache(CONST.HIVE_VERSION)?.ToString()}
                };
                JArray blobs = new JArray();
                JObject limit = new JObject();
                JObject attr = new JObject()
                {
                };
                int index = 1;
                foreach (var item in product.ScrewDatas)
                {
                    data.Add($"Screw{index}", item.Actual_Torque);
                    limit.Add($"Screw{index}", new JObject() {
                                            {"upper_limit", item.TorqueMax },
                                            {"lower_limit",  item.TorqueMin }
                    });
                    blobs.Add(new JObject() { { "file_name", item.FilePath + ".csv" } });
                    blobs.Add(new JObject() { { "file_name", item.FilePath + ".jpg" } });
                    index++;
                }

                JObject obj = new JObject()
                {
                    { "unit_sn",product.Barcode},
                    { "serials",serials},
                    { "pass",product.Accumulative_Result=="OK"?"true":"false"},
                    { "input_time",product.StartTime.ToString("yyyy-MM-ddTHH:mm:ss.f2+0800")},
                    { "output_time",product.EndTime?.ToString("yyyy-MM-ddTHH:mm:ss.f2+0800")},
                    { "data",data},
                    { "limit",limit},
                    { "attr",attr},
                    { "blobs",blobs},
                };
                Log4.Info("【Hive】请求:" + obj.ToString());
                var strRep = HttpRequest(obj);
                Log4.Info("【Hive】返回:" + strRep);

                if (strRep.Contains("Success"))
                {
                    product.HiveSuccess = true;
                    DBHelper.Instance.Sql.Updateable(product).ExecuteCommand();
                }
                else if (strRep.Contains("4"))
                {
                }
                else
                {

                }
            }
        }
        public string HttpRequest(JObject objHive)
        {
            string strResponse = string.Empty;
            try
            {
                string url = Cache.GetCache(CONST.HIVE_URL)?.ToString();
                url = "http://baidu.com";
                // 边界符  
                var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
                var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
                var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");              // 最后的结束符

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Timeout = 4000;
                var ms = new MemoryStream();
                request.Method = "POST";
                request.ContentType = "multipart/form-data;boundary=" + boundary;//multipart/form-data模式
                //string[] filePaths = GetFilepathsFromhivedata(hivedata);
                JArray array = JArray.Parse(objHive["blobs"].ToString());
                for (int i = 0; i < array.Count; i++)
                {
                    var item = JObject.Parse(array[i].ToString());
                    string filePath = item["file_name"].ToString();
                    if (File.Exists(filePath))
                    {
                        // 写入文件  
                        string header = $"Content-Disposition: form-data; name=\"file{i + 1}\"; filename=\"{filePath}\"\r\nContent-Type: {GetMimeMapping(filePath)}\r\n\r\n";
                        var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                        var headerbytes = Encoding.UTF8.GetBytes(header);
                        ms.Write(beginBoundary, 0, beginBoundary.Length);
                        ms.Write(headerbytes, 0, headerbytes.Length);
                        byte[] buffer = new byte[4096];
                        int bytesRead = 0;
                        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)//将文件内容写入流
                        {
                            ms.Write(buffer, 0, bytesRead);
                        }
                        fileStream.Close();
                        var enterbytes = Encoding.UTF8.GetBytes("\r\n");
                        ms.Write(enterbytes, 0, enterbytes.Length);
                    }
                }

                ms.Write(beginBoundary, 0, beginBoundary.Length);
                string strJson = string.Format("Content-Disposition: form-data; name=\"{0}\"" + "\r\n\r\n{1}\r\n", "jsondata", objHive.ToString());
                var databytes = Encoding.UTF8.GetBytes(strJson);
                ms.Write(databytes, 0, databytes.Length);
                ms.Write(endBoundary, 0, endBoundary.Length);
                request.ContentLength = ms.Length;
                request.Proxy = null;
                request.ServicePoint.Expect100Continue = false;
                Stream writer = request.GetRequestStream();

                ms.Position = 0;
                var tempBuffer = new byte[ms.Length];
                ms.Read(tempBuffer, 0, tempBuffer.Length);
                ms.Close();

                writer.Write(tempBuffer, 0, tempBuffer.Length);
                writer.Close();
                var response = (HttpWebResponse)request.GetResponse();
                var stream = response.GetResponseStream();

                StreamReader Reader = new StreamReader(stream, Encoding.UTF8);
                strResponse = Reader.ReadToEnd();
            }
            catch (Exception ex)
            {
                strResponse = ex.Message;
            }
            return strResponse;
        }
    }
}
